package Homework.Date7_02;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

/**
 * 3:在控制台输入一个学生的全部信息，保存到数据库， 注意日期的处理(PreparedStatement)
 * 
 * @author Y
 *
 */
public class InsertStudent {
	static {
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			System.out.println("驱动未找到!");
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		System.out.print("请输入姓名:");
		String name = in.next();
		System.out.print("请输入性别:");
		String sex = in.next();
		System.out.print("请输入手机号码:");
		long number = in.nextLong();
		System.out.print("请输入qq号码:");
		long qqnumber = in.nextLong();
		System.out.print("请输入年级:");
		int grade = in.nextInt();

		Datejudge da = new Datejudge();
		System.out.print("请输入入学日期:");
		String enter = null;
		while (true) {
			enter = in.next();
			if (da.validate(enter) == true) {
				System.out.println("输入正确!");
				break;
			}
			System.out.println("请按照正确格式输入:");
		}

		System.out.print("请输入生日:");
		String birthday = null;
		while (true) {
			birthday = in.next();
			if (da.validate(birthday) == true) {
				System.out.println("输入正确!");
				break;
			}
			System.out.println("请按照正确格式输入:");
		}

		String ur1 = "jdbc:mysql://localhost:3306/test?useSSL=false";
		Connection con = null;
		PreparedStatement sta = null;
		int re = 0;
		try {
			con = DriverManager.getConnection(ur1, "root", "zzq11475@");
			String sql = "insert into s_student(sname,sex,telephone,qq,gradeid,enterdate,birthday) values";
			sql += "(?,?,?,?,?,?,?)";
			sta = con.prepareStatement(sql);
			sta.setString(1, name);
			sta.setString(2, sex);
			sta.setLong(3, number);
			sta.setLong(4, qqnumber);
			sta.setInt(5, grade);
			sta.setString(6, enter);
			sta.setString(7, birthday);
			re = sta.executeUpdate();
			System.out.println("改变了" + re + "数据");
		} catch (SQLException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} finally {
			try {
				if (con != null) {
					con.close();
				}
			} catch (SQLException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
			try {
				if (sta != null) {
					sta.close();
				}
			} catch (SQLException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
			System.out.println("资源释放完成");
		}
	}

}
